<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="关联用户ID" prop="userId">
        <el-select class="!w-240px" v-model="queryParams.userId" placeholder="请选择用户" clearable filterable >
          <el-option
              v-for="dict in userList"
              :key="dict.id"
              :label="dict.nickname"
              :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车辆品牌" prop="vehicleBrand">
        <el-input
          v-model="queryParams.vehicleBrand"
          placeholder="请输入车辆品牌"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="车辆型号" prop="vehicleModel">
        <el-input
          v-model="queryParams.vehicleModel"
          placeholder="请输入车辆型号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="购置日期" prop="purchaseDate">
        <el-date-picker
          v-model="queryParams.purchaseDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="行驶里程（公里）" prop="mileage">
        <el-input
          v-model="queryParams.mileage"
          placeholder="请输入行驶里程（公里）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="评估价值（元）" prop="assessedValue">
        <el-input
          v-model="queryParams.assessedValue"
          placeholder="请输入评估价值（元）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="登记证书编号" prop="registrationNumber">
        <el-input
          v-model="queryParams.registrationNumber"
          placeholder="请输入登记证书编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="行驶证照片路径" prop="licensePhoto">
        <el-input
          v-model="queryParams.licensePhoto"
          placeholder="请输入行驶证照片路径"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="抵押状态" prop="mortgageStatus">
        <el-select
          v-model="queryParams.mortgageStatus"
          placeholder="请选择抵押状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MORTGAGE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:car-mortgage:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:car-mortgage:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="车辆品牌" align="center" prop="vehicleBrand" />
      <el-table-column label="车辆型号" align="center" prop="vehicleModel" />
      <el-table-column
        label="购置日期"
        align="center"
        prop="purchaseDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="行驶里程（公里）" align="center" prop="mileage" />
      <el-table-column label="评估价值（元）" align="center" prop="assessedValue" />
      <el-table-column label="登记证书编号" align="center" prop="registrationNumber" />
      <el-table-column label="行驶证照片" align="center" prop="licensePhoto" >
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.licensePhoto"
              :zoom-rate="1.2"
              :preview-src-list="[scope.row.licensePhoto]"
              :initial-index="0"
              fit="cover"
              hide-on-click-modal
              preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="抵押状态" align="center" prop="mortgageStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MORTGAGE" :value="scope.row.mortgageStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:car-mortgage:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:car-mortgage:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CarMortgageForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CarMortgageApi, CarMortgageVO } from '@/api/system/carmortgage'
import CarMortgageForm from './CarMortgageForm.vue'
import {getMemberUserAll} from "@/api/member/user";

/** 车辆抵押贷款信息 列表 */
defineOptions({ name: 'CarMortgage' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userList = ref([])

const loading = ref(true) // 列表的加载中
const list = ref<CarMortgageVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  vehicleBrand: undefined,
  vehicleModel: undefined,
  purchaseDate: [],
  mileage: undefined,
  assessedValue: undefined,
  registrationNumber: undefined,
  licensePhoto: undefined,
  mortgageStatus: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CarMortgageApi.getCarMortgagePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CarMortgageApi.deleteCarMortgage(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CarMortgageApi.exportCarMortgage(queryParams)
    download.excel(data, '车辆抵押贷款信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const getUserList = async () => {
  try {
    // 修正：添加括号调用函数
    const data = await getMemberUserAll()
    console.log('用户列表数据:', data)
    // 修正：使用.value赋值给ref
    userList.value = data
  } catch (error) {
    console.error('获取用户列表失败', error)
    message.error('获取用户列表失败')
  }
}
/** 初始化 **/
onMounted(() => {
  getUserList()
  getList()
})
</script>
